package org.jeecg.modules.wms.outOrder.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.wms.auditOut.entity.WmsAuditOut;
import org.jeecg.modules.wms.auditOut.service.IWmsAuditOutService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wms.outOrder.entity.WmsOutOrderLine;
import org.jeecg.modules.wms.outOrder.entity.WmsOutOrderHeader;
import org.jeecg.modules.wms.outOrder.vo.WmsOutOrderHeaderPage;
import org.jeecg.modules.wms.outOrder.service.IWmsOutOrderHeaderService;
import org.jeecg.modules.wms.outOrder.service.IWmsOutOrderLineService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 出库单主表
 * @Author: jeecg-boot
 * @Date:   2023-11-13
 * @Version: V1.0
 */
@Api(tags="出库单主表")
@RestController
@RequestMapping("/outOrder/wmsOutOrderHeader")
@Slf4j
public class WmsOutOrderHeaderController {
	@Autowired
	private IWmsOutOrderHeaderService wmsOutOrderHeaderService;
	@Autowired
	private IWmsOutOrderLineService wmsOutOrderLineService;
	 @Autowired
	 private IWmsAuditOutService wmsAuditOutService;
	
	/**
	 * 分页列表查询
	 *
	 * @param wmsOutOrderHeader
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "出库单主表-分页列表查询")
	@ApiOperation(value="出库单主表-分页列表查询", notes="出库单主表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<WmsOutOrderHeader>> queryPageList(WmsOutOrderHeader wmsOutOrderHeader,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WmsOutOrderHeader> queryWrapper = QueryGenerator.initQueryWrapper(wmsOutOrderHeader, req.getParameterMap());
		Page<WmsOutOrderHeader> page = new Page<WmsOutOrderHeader>(pageNo, pageSize);
		IPage<WmsOutOrderHeader> pageList = wmsOutOrderHeaderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param wmsOutOrderHeaderPage
	 * @return
	 */
	@AutoLog(value = "出库单主表-添加")
	@ApiOperation(value="出库单主表-添加", notes="出库单主表-添加")
    @RequiresPermissions("outOrder:wms_out_order_header:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody WmsOutOrderHeaderPage wmsOutOrderHeaderPage) {
		WmsOutOrderHeader wmsOutOrderHeader = new WmsOutOrderHeader();
		BeanUtils.copyProperties(wmsOutOrderHeaderPage, wmsOutOrderHeader);
		wmsOutOrderHeaderService.saveMainOutOrderHeader(wmsOutOrderHeader, wmsOutOrderHeaderPage.getWmsOutOrderLineList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param wmsOutOrderHeaderPage
	 * @return
	 */
	@AutoLog(value = "出库单主表-编辑")
	@ApiOperation(value="出库单主表-编辑", notes="出库单主表-编辑")
    @RequiresPermissions("outOrder:wms_out_order_header:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody WmsOutOrderHeaderPage wmsOutOrderHeaderPage) {
		WmsOutOrderHeader wmsOutOrderHeader = new WmsOutOrderHeader();
		BeanUtils.copyProperties(wmsOutOrderHeaderPage, wmsOutOrderHeader);
		WmsOutOrderHeader wmsOutOrderHeaderEntity = wmsOutOrderHeaderService.getById(wmsOutOrderHeader.getId());
		if(wmsOutOrderHeaderEntity==null) {
			return Result.error("未找到对应数据");
		}
		wmsOutOrderHeader.setOrderNum(wmsOutOrderHeaderEntity.getOrderNum());
		wmsOutOrderHeader.setOrderStatus(wmsOutOrderHeaderEntity.getOrderStatus());
		wmsOutOrderHeaderService.updateMain(wmsOutOrderHeader, wmsOutOrderHeaderPage.getWmsOutOrderLineList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出库单主表-通过id删除")
	@ApiOperation(value="出库单主表-通过id删除", notes="出库单主表-通过id删除")
    @RequiresPermissions("outOrder:wms_out_order_header:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		wmsOutOrderHeaderService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出库单主表-批量删除")
	@ApiOperation(value="出库单主表-批量删除", notes="出库单主表-批量删除")
    @RequiresPermissions("outOrder:wms_out_order_header:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.wmsOutOrderHeaderService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "出库单主表-通过id查询")
	@ApiOperation(value="出库单主表-通过id查询", notes="出库单主表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<WmsOutOrderHeader> queryById(@RequestParam(name="id",required=true) String id) {
		WmsOutOrderHeader wmsOutOrderHeader = wmsOutOrderHeaderService.getById(id);
		if(wmsOutOrderHeader==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(wmsOutOrderHeader);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "出库单子表-通过主表ID查询")
	@ApiOperation(value="出库单子表-通过主表ID查询", notes="出库单子表-通过主表ID查询")
	@GetMapping(value = "/queryWmsOutOrderLineByMainId")
	public Result<IPage<WmsOutOrderLine>> queryWmsOutOrderLineListByMainId(@RequestParam(name="id",required=true) String id) {
		WmsOutOrderHeader outOrderHeader = wmsOutOrderHeaderService.getById(id);
		List<WmsOutOrderLine> wmsOutOrderLineList = wmsOutOrderLineService.selectByMainId(outOrderHeader.getOrderNum());
		for (WmsOutOrderLine wmsOutOrderLine : wmsOutOrderLineList) {
			WmsAuditOut wmsAuditOut = wmsAuditOutService.getOne(new LambdaQueryWrapper<WmsAuditOut>().eq(
					WmsAuditOut::getLineOrderId, wmsOutOrderLine.getId()
			));
			if (wmsAuditOut != null) {
				wmsOutOrderLine.setGoodsOkQua(wmsAuditOut.getShelfOkQua());
				wmsOutOrderLine.setGoodsSyQua(wmsAuditOut.getShelfSyQua());
			}
		}
		IPage <WmsOutOrderLine> page = new Page<>();
		page.setRecords(wmsOutOrderLineList);
		page.setTotal(wmsOutOrderLineList.size());
		return Result.OK(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param wmsOutOrderHeader
    */
    @RequiresPermissions("outOrder:wms_out_order_header:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmsOutOrderHeader wmsOutOrderHeader) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<WmsOutOrderHeader> queryWrapper = QueryGenerator.initQueryWrapper(wmsOutOrderHeader, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<WmsOutOrderHeader>  wmsOutOrderHeaderList = wmsOutOrderHeaderService.list(queryWrapper);

      // Step.3 组装pageList
      List<WmsOutOrderHeaderPage> pageList = new ArrayList<WmsOutOrderHeaderPage>();
      for (WmsOutOrderHeader main : wmsOutOrderHeaderList) {
          WmsOutOrderHeaderPage vo = new WmsOutOrderHeaderPage();
          BeanUtils.copyProperties(main, vo);
          List<WmsOutOrderLine> wmsOutOrderLineList = wmsOutOrderLineService.selectByMainId(main.getId());
          vo.setWmsOutOrderLineList(wmsOutOrderLineList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "出库单主表列表");
      mv.addObject(NormalExcelConstants.CLASS, WmsOutOrderHeaderPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库单主表数据", "导出人:"+sysUser.getRealname(), "出库单主表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("outOrder:wms_out_order_header:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<WmsOutOrderHeaderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), WmsOutOrderHeaderPage.class, params);
              for (WmsOutOrderHeaderPage page : list) {
                  WmsOutOrderHeader po = new WmsOutOrderHeader();
                  BeanUtils.copyProperties(page, po);
                  wmsOutOrderHeaderService.saveMain(po, page.getWmsOutOrderLineList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
